package pers.cnzdy.tutorial.Chapter9_Perception_Media.Section5_Camera;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import pers.cnzdy.tutorial.R;

public class CameraActivity extends AppCompatActivity {
    public static final int TAKE_PICTURE = 1;

    private Button takePicture;
    private ImageView picture;
    private Uri picUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        requestPermission();

        takePicture = findViewById(R.id.take_picture);
        picture = findViewById(R.id.picture);
        takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File savePicture = new File(getExternalCacheDir(), "MyPicture.jpg");
                try {
                    if (savePicture.exists()) {
                        savePicture.delete();
                    }
                    savePicture.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (Build.VERSION.SDK_INT >=24) {
                    picUri = FileProvider.getUriForFile(CameraActivity.this,
                            "pers.cnzdy.tutorial.provider", savePicture);
                } else {
                    picUri = Uri.fromFile(savePicture);
                }

                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
                startActivityForResult(intent, TAKE_PICTURE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (resultCode == RESULT_OK) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(
                                getContentResolver().openInputStream(picUri));
                        picture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 申请权限
     */
    public static final int CAMERA_REQ_CODE = 111;

    private void requestPermission() {
        // 判断当前Activity是否已经获得了该权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
                Toast.makeText(CameraActivity.this,
                        "请进入设置-应用管理-打开相机权限",
                        Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions( // 进行权限请求
                        this,
                        new String[]{Manifest.permission.CAMERA},
                        CAMERA_REQ_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[],
                                           int[] grantResults) {
        switch (requestCode) {
            case CAMERA_REQ_CODE: { // 如果请求被拒绝，那么通常grantResults数组为空
                if (grantResults.length > 0 && grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED) {
                    // 申请成功，进行相应操作
                } else { // 申请失败，可以继续向用户解释。
                    Toast.makeText(CameraActivity.this,
                            "没有相机权限,您可能无法使用相机",
                            Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }
}
